const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const path = require('path')
const express = require('express');
const app = express()
app.use(express.static('client'))
 
const server = https.createServer({
    key: fs.readFileSync(path.resolve('./CA/key.pem')),
    cert: fs.readFileSync(path.resolve('./CA/cert.pem'))
},app);

// const server = http.createServer({},app);
const wss = new WebSocket.Server({ server });
 
const userSocketMap = {}

wss.on('connection', function connection(ws) {
  ws.on('message', (message) => {
    console.log('message-------',message)
    const {type,from,to} = JSON.parse(message)
    if(to === 'service'){
      if(type === 'login'){
        userSocketMap[from] = ws
      }
    }else{
      const targetSocket = userSocketMap[to]
      if(targetSocket){
        targetSocket.send(message)
      }else{
        ws.send(JSON.stringify({
          from:to,
          to:from,
          type:'reject_call',
          data:'该用户不在线'
        }))
      }
    }
  });
  ws.on('close',() => {
    for (userId of Object.keys(userSocketMap) ){
      if(ws === userSocketMap[userId]){
        delete userSocketMap[userId]
        return
      }
    }
  })
});
server.listen(443,() => {
  console.log('服务器启动成功...')
})